﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using OrchardSystemServer.Account;

namespace OrchardSystemServer.Log
{
    public class LogToListBox
    {
        private ListBox listbox;

        private delegate void AddItemDelegate(string str);
        private AddItemDelegate addItemDelegateWithTime;
        private AddItemDelegate addItemDelegate;


        private delegate void ClearItemDelegate();
        private ClearItemDelegate clearItemDelegate;
        public LogToListBox(ListBox listbox)
        {
            this.listbox = listbox;
            addItemDelegateWithTime = new AddItemDelegate(AddItemWithTime);
            addItemDelegate = new AddItemDelegate(AddItem);
            clearItemDelegate = new ClearItemDelegate(ClearItem);
        }

        /// <summary>
        /// 在listbox中追加信息
        /// </summary>
        /// <param name="str">要追加的信息</param>
        public void AddItemWithTime(string str)
        {

            if (listbox.InvokeRequired)
            {
                listbox.Invoke(addItemDelegateWithTime, str);
            }
            else
            {
                string strTemp = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + "----->" + str;
                listbox.Items.Add(strTemp);
                listbox.SelectedIndex = listbox.Items.Count - 1;
            }
        }


        /// <summary>
        /// 在listbox中追加信息
        /// </summary>
        /// <param name="str">要追加的信息</param>
        public void AddItem(string str)
        {
            if (listbox.InvokeRequired)
            {
                listbox.Invoke(addItemDelegate, str);
            }
            else
            {
                listbox.Items.Add(str);
                listbox.SelectedIndex = listbox.Items.Count - 1;
                listbox.ClearSelected();//清除选中状态
            }
        }

        /// <summary>
        /// 清空所有项
        /// </summary>
        public void ClearItem()
        {
            if (listbox.InvokeRequired)
            {
                listbox.Invoke(clearItemDelegate);
            }
            else
            {
                listbox.Items.Clear();
            }
        }
    }
}
